from pyrad import dictionary, packet, server
import logging

logger = logging.getLogger("online_notice_server")
logging.basicConfig(filename="online_notice.log", level="INFO")


def handle_msg(username, ip_addr):
    """do something after parsing
    """
    logger.info("username: {} ip: {}".format(username, ip_addr))
    pass


class OnlineNoticeServer(server.Server):
    def HandleAcctPacket(self, pkt):
        logger.debug("Accounting request received")
        logger.debug("get attributes")

        msg = ["", ""]

        try:
            for attr in pkt.keys():
                if attr == "User-Name":
                    msg[0] = pkt[attr][0]
                elif attr == "Framed-IP-Address":
                    msg[1] = pkt[attr][0]
        except IndexError as e:
            # the packet is not alright?
            logger.debug("index error!")
            return

        logger.debug("got message:" + str(msg))

        handle_msg(msg[0], msg[1])


if __name__ == "__main__":
    logger.info("Server start on localhost")
    notice_server = OnlineNoticeServer(dict=dictionary.Dictionary("dictionary"))
    # secret key should be changed
    secret_key = b'12345'
    notice_server.hosts['127.0.0.1'] = server.RemoteHost("127.0.0.1", secret_key, "localhost")
    notice_server.BindToAddress("")

    notice_server.Run()
